package com.vsu.bookstore.mvc.ui.widgetcontainers;

import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;
import com.vsu.bookstore.BookstoreApplication;
import com.vsu.bookstore.mvc.model.bean.BookStoreItem;
import com.vsu.bookstore.mvc.ui.NavigationButtonView;
import com.vsu.bookstore.mvc.ui.widgets.TableContainer;
import com.vsu.bookstore.mvc.ui.window.CheckoutWindow;
import com.vsu.bookstore.mvc.ui.window.ItemWindow;
import com.vsu.bookstore.util.DataUtils;

@SuppressWarnings("serial")
public class UiHandler extends VerticalLayout
{
  private final MainPanel mainPanel = new MainPanel();

  private final NavigationButtonView header = new NavigationButtonView();

  private final TableContainer tableContainer = new TableContainer();

  private final ItemWindow itemWindow = new ItemWindow();

  private final CartPanel cartPanel = new CartPanel();

  private final HorizontalLayout layout = new HorizontalLayout();

  private final VerticalLayout cartLayout = new VerticalLayout();

  private CheckoutWindow checkoutWindow = null;

  public UiHandler()
  {
    super();
    setSizeFull();
    setMargin(false);
    setSpacing(false);
    layout.setSizeFull();
    layout.setSpacing(true);
    layout.setMargin(true, false, true, true);
    layout.addComponent(tableContainer);
    cartLayout.setMargin(false);
    cartLayout.setSpacing(false);
    cartLayout.addComponent(header);
    cartLayout.addComponent(cartPanel);
    cartLayout.setSizeFull();
    cartLayout.setExpandRatio(cartPanel, 1.0f);
    layout.addComponent(cartLayout);
    layout.setExpandRatio(tableContainer, 0.8f);
    layout.setExpandRatio(cartLayout, 0.3f);
    mainPanel.setMainView(layout);
    addComponent(mainPanel);
    setExpandRatio(mainPanel, 1f);
  }

  public void addTableItem(final BookStoreItem bean)
  {
    DataUtils.addBookStoreItem(bean);
    tableContainer.onCategoryUpdated(bean);
  }

  public void addToCartPanel(final BookStoreItem bean, final boolean isAdding)
  {
    cartPanel.updateItem(bean, isAdding);
  }

  public void checkout()
  {
    if (checkoutWindow == null)
      checkoutWindow = new CheckoutWindow(((BookstoreApplication)getApplication()).getSession());
    checkoutWindow.beforeShow();
    getWindow().addWindow(checkoutWindow);
  }

  public void clearCartPanel()
  {
    cartPanel.removeAllPreviews();
  }

  public void createNewItem()
  {
    itemWindow.setContentsLocked(false);
    itemWindow.resetItemDS(new BookStoreItem());
    getWindow().addWindow(itemWindow);
  }

  public void onCategoryHeaderDblClicked(final Object id)
  {
    tableContainer.changeVisibilyState(id);
  }

  public void showDetailed(final BookStoreItem itemId)
  {
    if (itemId == null)
      return;
    itemWindow.setContentsLocked(true);
    itemWindow.resetItemDS(itemId);
    getWindow().addWindow(itemWindow);
  }
}
